<template>
  <div class="reset-password-container">
    <div class="password-card">
      <div class="card-header">
        <div class="card-icon">
          <el-icon><Lock /></el-icon>
        </div>
        <div class="card-text">
          <h2 class="card-title">修改密码</h2>
          <p class="card-description">更新您的账号密码，保障账户安全</p>
        </div>
      </div>

      <el-divider />

      <div class="password-form">
        <div class="form-row">
          <label class="form-label">用户名</label>
          <div class="el-input">
            <el-input
                v-model="user.username"
                placeholder="请输入用户名"
                disabled
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </div>
        </div>

        <div class="form-row">
          <label class="form-label"><span>*</span> 原密码</label>
          <div class="el-input">
            <el-input
                v-model="passwordForm.oldPassword"
                placeholder="请输入原密码"
                type="password"
                show-password
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
          </div>
        </div>

        <div class="form-row">
          <label class="form-label"><span>*</span> 新密码</label>
          <div class="el-input">
            <el-input
                v-model="passwordForm.newPassword"
                placeholder="请输入新密码（至少8位）"
                type="password"
                show-password
                @input="checkPasswordStrength"
            >
              <template #prefix>
                <el-icon><Unlock /></el-icon>
              </template>
            </el-input>
          </div>

          <div class="password-strength">
            <div
                v-for="i in 4"
                :key="i"
                class="strength-segment"
                :style="{background: strengthColors[i-1]}"
            ></div>
          </div>
          <div class="strength-text">密码强度：{{ strengthText }}</div>
        </div>

        <div class="form-row">
          <label class="form-label"><span>*</span> 确认新密码</label>
          <div class="el-input">
            <el-input
                v-model="passwordForm.confirmPassword"
                placeholder="请再次输入新密码"
                type="password"
                show-password
                @input="validatePasswordMatch"
            >
              <template #prefix>
                <el-icon><CircleCheck /></el-icon>
              </template>
            </el-input>
          </div>
          <div v-if="passwordMismatch" class="error-message">
            两次输入的密码不一致
          </div>
        </div>

        <div class="password-rules">
          <div class="rules-title">密码安全要求：</div>
          <div class="rule-item">
            <el-icon><Warning /></el-icon> 至少8个字符
          </div>
          <div class="rule-item">
            <el-icon><Warning /></el-icon> 包含大写字母、小写字母和数字
          </div>
          <div class="rule-item">
            <el-icon><Warning /></el-icon> 可包含特殊字符 @$!%*?&
          </div>
          <div class="rule-item">
            <el-icon><Warning /></el-icon> 不能与旧密码相同
          </div>
          <div class="rule-item">
            <el-icon><Warning /></el-icon> 建议每90天更换一次密码
          </div>
        </div>

        <div class="form-actions">
          <el-button class="cancel-btn" @click="resetForm">重置</el-button>
          <el-button
              class="submit-btn"
              @click="submitForm"
              :loading="loading"
          >
            保存更改
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import {
  Lock, User, Key, Unlock, CircleCheck, Warning
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import http from '@/util/http.js'; // 使用项目中的http工具
import api from '@/api/index.js'; // 使用项目中的API模块

export default {
  name: 'ResetPassword',
  components: {
    Lock,
    User,
    Key,
    Unlock,
    CircleCheck,
    Warning
  },
  setup() {
    const loading = ref(false);

    // 从sessionStorage获取用户信息
    const user = reactive({
      username: "",
      name: "",
      position: ""
    });

    // 密码表单数据
    const passwordForm = reactive({
      oldPassword: "",
      newPassword: "",
      confirmPassword: ""
    });

    // 密码强度状态
    const strengthColors = ref(["#e0e0e0", "#e0e0e0", "#e0e0e0", "#e0e0e0"]);
    const strengthText = ref("低");
    const passwordMismatch = ref(false);

    // 初始化用户数据
    const initUserData = () => {
      const userData = JSON.parse(sessionStorage.getItem('user') || '{}');
      user.username = userData.username || "未知用户";
      user.name = userData.name || "";
      user.position = userData.position || "";
    };

    // 检查密码强度
    const checkPasswordStrength = () => {
      const password = passwordForm.newPassword;

      if (!password) {
        resetStrength();
        return;
      }

      // 计算密码强度
      let strength = 0;

      // 长度检查
      if (password.length >= 8) strength += 1;

      // 字符种类检查
      const hasLower = /[a-z]/.test(password);
      const hasUpper = /[A-Z]/.test(password);
      const hasDigit = /[0-9]/.test(password);
      const hasSpecial = /[@$!%*?&]/.test(password);

      // 至少包含两种字符类型
      const charTypes = [hasLower, hasUpper, hasDigit, hasSpecial].filter(Boolean).length;

      if (charTypes >= 2) strength += 1;
      if (charTypes >= 3) strength += 1;
      if (charTypes === 4) strength += 1;

      // 更新强度指示器
      updateStrengthIndicator(strength);
    };

    const resetStrength = () => {
      strengthColors.value = ["#e0e0e0", "#e0e0e0", "#e0e0e0", "#e0e0e0"];
      strengthText.value = "低";
    };

    const updateStrengthIndicator = (strength) => {
      const colors = [];
      const strengthLabels = ["低", "中低", "中", "中高", "高"];

      for (let i = 0; i < 4; i++) {
        if (i < Math.min(strength, 4)) {
          const colorMap = {
            1: "#ff4d4f", // 弱
            2: "#faad14", // 中等
            3: "#52c41a", // 强
            4: "#389e0d"  // 非常强
          };
          colors.push(colorMap[Math.min(strength, 4)]);
        } else {
          colors.push("#e0e0e0");
        }
      }

      strengthColors.value = colors;
      strengthText.value = strengthLabels[Math.min(strength, 4)];
    };

    // 验证密码匹配
    const validatePasswordMatch = () => {
      if (passwordForm.newPassword && passwordForm.confirmPassword &&
          passwordForm.newPassword !== passwordForm.confirmPassword) {
        passwordMismatch.value = true;
      } else {
        passwordMismatch.value = false;
      }
    };

    // 提交表单
    const submitForm = async () => {
      // 验证原密码
      if (!passwordForm.oldPassword) {
        ElMessage.error('请输入原密码');
        return;
      }

      // 验证新密码长度
      if (!passwordForm.newPassword || passwordForm.newPassword.length < 8) {
        ElMessage.error('新密码长度必须至少8位');
        return;
      }

      // 验证密码一致性
      if (!passwordForm.confirmPassword || passwordForm.confirmPassword !== passwordForm.newPassword) {
        ElMessage.error('两次输入的新密码不一致');
        return;
      }

      // 验证新旧密码是否相同
      if (passwordForm.oldPassword === passwordForm.newPassword) {
        ElMessage.error('新密码不能与原密码相同');
        return;
      }

      // 验证密码强度（至少中等强度）
      if (strengthText.value === "低" || strengthText.value === "中低") {
        ElMessage.warning('密码强度不足，请使用更复杂的密码');
        return;
      }

      try {
        loading.value = true;

        // 调用API修改密码
        const response = await api.updatePassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword
        });

        if (response.code === 200) {
          ElMessage.success('密码修改成功！');
          resetForm();
        } else {
          ElMessage.error(response.msg || '密码修改失败');
        }
      } catch (error) {
        console.error('修改密码出错:', error);
        ElMessage.error('修改密码失败，请重试');
      } finally {
        loading.value = false;
      }
    };

    // 重置表单
    const resetForm = () => {
      passwordForm.oldPassword = "";
      passwordForm.newPassword = "";
      passwordForm.confirmPassword = "";
      passwordMismatch.value = false;
      resetStrength();
    };

    onMounted(() => {
      initUserData();
    });

    return {
      user,
      passwordForm,
      strengthColors,
      strengthText,
      passwordMismatch,
      loading,
      checkPasswordStrength,
      validatePasswordMatch,
      submitForm,
      resetForm
    };
  }
}
</script>

<style scoped>
/* 保持原有的样式不变 */
.reset-password-container {
  background-color: #f7f9fc;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.password-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 500px;
  max-width: 95%;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #e6f7ff, #b3e0ff);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
}

.card-icon .el-icon {
  font-size: 28px;
  color: #1e88e5;
}

.card-text {
  flex: 1;
}

.card-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.card-description {
  font-size: 15px;
  color: #666;
}

.el-divider {
  margin: 25px 0;
}

.password-form {
  padding: 10px 0;
}

.form-row {
  margin-bottom: 28px;
}

.form-label {
  display: block;
  margin-bottom: 12px;
  font-size: 15px;
  color: #555;
  font-weight: 600;
}

.form-label span {
  color: #c20c0c;
}

.password-strength {
  margin-top: 10px;
  display: flex;
  height: 8px;
  border-radius: 4px;
  overflow: hidden;
}

.strength-segment {
  flex: 1;
  background: #e0e0e0;
  margin: 0 2px;
  border-radius: 2px;
  transition: all 0.3s;
}

.strength-text {
  font-size: 13px;
  color: #666;
  margin-top: 8px;
  font-weight: 500;
}

.password-rules {
  background: #f7f9fc;
  padding: 18px;
  border-radius: 8px;
  border-left: 4px solid #ffdf40;
  margin-top: 30px;
  margin-bottom: 15px;
}

.rules-title {
  color: #333;
  font-weight: bold;
  margin-bottom: 12px;
  font-size: 16px;
}

.rule-item {
  font-size: 14px;
  color: #555;
  line-height: 1.6;
  margin-bottom: 7px;
  display: flex;
  align-items: center;
}

.rule-item .el-icon {
  color: #ffb300;
  margin-right: 10px;
  font-size: 16px;
}

.form-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.error-message {
  color: #c20c0c;
  font-size: 14px;
  margin-top: 8px;
}

.submit-btn {
  background: linear-gradient(to right, #c20c0c, #8e0000);
  color: white;
  border: none;
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 600;
  letter-spacing: 1px;
  box-shadow: 0 4px 15px rgba(194, 12, 12, 0.2);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(194, 12, 12, 0.3);
}

.cancel-btn {
  background: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 600;
}

.cancel-btn:hover {
  border-color: #c0c4cc;
  background-color: #f5f7fa;
}

@media (max-width: 600px) {
  .password-card {
    padding: 25px;
  }

  .card-header {
    flex-direction: column;
    text-align: center;
  }

  .card-icon {
    margin-right: 0;
    margin-bottom: 15px;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}
</style>